# encoding: utf-8

module Capevaluation
  module WebService
    class CapevaluationMockSinatra < CaiQiu::WebService::CaiQiuMockSinatra

      # 客户端的接口
      post '/api/:cmd' do
        JSON.generate(mock_api(params))
      end

      # 客户端的接口
      post '/api' do
        JSON.generate(mock_api(params))
      end

      def mock_api(params)
        cmd_name = params[:cmd]
        mock_file = File.dirname(__FILE__) + "/../../../mock/#{cmd_name}.json"
        mock_data = CaiQiu::Support::Config.get_json(mock_file)
        mock_data.each {|data|
          # 找到最匹配的参数
          data['match_count'] = 0
          data['params'].each do |k, v|
            if defined? params["#{k}"] and params["#{k}"] == v
              data['match_count'] = data['match_count'] + 1
            end
          end
        }
        # 根据匹配度进行排序
        mock_data = mock_data.sort_by {|k| k['match_count']}.reverse
        mock_data[0]['resp']
      end

    end
  end
end